// pages/orderDetails/orderDetails.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    domain: app.api.domain,
    details: '',
    user_note: '',
    reasons: [
      '订单不能及时送达',
      '操作有误（商品、地址等选错）',
      '重复下单/误下单',
      '其他渠道价格更低',
      '该商品降价了',
      '不想买了'
    ],
    submit: 1,
    isallphone: 0,
    crdphoneNum: '',
    jrdphoneNum: '',
    qiyephoneNum: '',
    doublephoones: '',
    showModal: false,
    concent_list: ['微信支付', '会员卡支付'],
    curindex: 0
  },
  // 去申请售后
  toAfterSale(e) {
    console.log(e)
    wx.navigateTo({
      url: `/page/detail/pages/applyAfterSale/applyAfterSale?orderid=${e.currentTarget.dataset.orderid}&order_sn=${e.currentTarget.dataset.order_sn}`
    })
  },
  //联系快递员
  phone(e) {
    let phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone //仅为示例，并非真实的电话号码
    })
  },
  // 点击分享
  onShareAppMessage: function (res) {
    const that = this;
    console.log(res);

    let token = app.globalData.token;
    let goodsid = res.target.dataset.goodsid;
    let foundid = res.target.dataset.fdid;
    let shareimg = res.target.dataset.shareimg;
    let sharetitle = res.target.dataset.sharetitle;
    console.log(token, goodsid, foundid, shareimg, sharetitle);
    return {
      title: sharetitle,
      path: `/page/detail/pages/assenbleInfo/assenbleInfo?id=${goodsid}&foundid=${foundid}`, // 分享后打开的页面
      imageUrl: that.data.domain + shareimg
    }
  },
  toGoodsDetail(e) {
    const that = this;
    let id = e.currentTarget.dataset.id;
    let teamId = e.currentTarget.dataset.promid;
    let type = e.currentTarget.dataset.promtype;
    if (type == '6') {
      wx.navigateTo({
        url: `/page/detail/pages/assembleDetails/assembleDetails?id=${id}&teamid=${teamId}&from=1`
      })
    } else {
      wx.navigateTo({
        url: `/page/detail/pages/details/details?id=${id}`
      })
    }
  },
  //立即评价
  toEvaluate() {
    wx.navigateTo({
      url: '/page/detail/pages/myComments/myComments?index=1',
    })
  },

  // 确认收货
  confirmReceive(e) {
    const that = this;
    let order_id = e.currentTarget.dataset.sn;
    let json = {
      token: app.globalData.token,
      order_id
    }
    let jsonData = app.utils.getSignData(json)
    that.setData({
      hiddenLoading: false
    })
    wx.showModal({
      content: '是否确认收货',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(e) {
        if (e.confirm) {
          app.utils.post(app.api.reqUrls.orderConfirm, jsonData).then(res => {
            that.setData({
              hiddenLoading: true
            })
            console.log(res)
            if (res.status == 1) {
              app.showInfo(res.msg)
              that.getDetails();
            } else {
              throw res.msg
            }
          }).catch(err => {
            app.showInfo(err.toString());
            that.setData({
              hiddenLoading: true
            })
          })
        } else {
          that.setData({
            hiddenLoading: true
          })
        }
      },
      fail() {
        that.setData({
          hiddenLoading: true
        })
      }
    })
    that.setData({
      hiddenLoading: true
    })

  },


  // 取消订单
  cancelOrder(e) {
    const that = this;
    let status = e.currentTarget.dataset.status;
    let id = that.data.details.order_id;
    if (status == "待支付") {
      let json = {
        token: app.globalData.token,
        order_id_sn: that.data.id + '=' + that.data.sn,
      }
      let jsonData = app.utils.getSignData(json);

      wx.showModal({
        content: '是否取消该订单',
        confirmText: '确定',
        confirmColor: '#ff5151',
        success(e) {
          if (e.confirm) {
            that.setData({
              hiddenLoading: false
            })
            app.utils.post(app.api.reqUrls.cancelOrder, jsonData).then(res => {
              that.setData({
                hiddenLoading: true
              })
              app.showInfo(res.msg)
              that.getDetails();
            }).catch(err => {
              app.showInfo(err.toString())
            })
          }
        }
      })
    } else { // 取消已支付订单
      wx.showActionSheet({
        itemList: that.data.reasons,
        success(res) {
          let json = {
            token: app.globalData.token,
            order_id: that.data.id,
            consignee: that.data.details.consignee,
            mobile: that.data.details.mobile,
            user_note: that.data.reasons[res.tapIndex],
            is_json: 1
          }
          let jsonData = app.utils.getSignData(json);

          wx.showModal({
            content: '是否取消该订单',
            confirmText: '确定',
            confirmColor: '#ff5151',
            success(e) {
              if (e.confirm) {
                that.setData({
                  hiddenLoading: false
                })
                app.utils.post(app.api.reqUrls.cancelPaidOrder, jsonData).then(res => {
                  console.log(res)
                  that.setData({
                    hiddenLoading: true
                  })
                  if (res.status == 1) {
                    app.showInfo(res.msg);
                    that.getDetails();
                  } else {
                    throw res.msg
                  }
                }).catch(err => {
                  app.showInfo(err.toString());
                  that.setData({
                    hiddenLoading: true
                  })
                })
              }
            }
          })
        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    }
  },

  // 获取数据
  getDetails() {
    const that = this;
    let json = {
      token: app.globalData.token,
      order_id_sn: that.data.id + '=' + that.data.sn,
      store_id: that.data.storeid,
      // id: that.data.id,
      // sn: that.data.sn
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.getOrderDetail, jsonData).then(res => {
      console.log(res)
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {

        res.result.stores.forEach(item => {
          app.getImg(item.goods);
        })

        if (res.result.stores.length >= 2) {

          let doublephoone = [];
          res.result.stores.forEach(items => {
            if (items.store_type == 1) {
              doublephoone.push('客服：' + items.store_phone);
            }
            if (items.store_type == 0) {
              doublephoone.push('客服：' + items.store_phone);
            }
            if (items.store_type == 2) {
              doublephoone.push('客服：' + items.store_phone);
            }
          })
          that.setData({
            doublephoones: doublephoone,
            isallphone: 0
          })
        } else {
          if (res.result.stores) {
            res.result.stores.forEach(items => {
              if (items.store_type == 1) {
                that.setData({
                  crdphoneNum: items.store_phone,
                  isallphone: 1
                })

              } else if (items.store_type == 0) {
                that.setData({
                  jrdphoneNum: items.store_phone,
                  isallphone: 2
                })

              } else if (items.store_type == 2) {
                that.setData({
                  qiyephoneNum: items.store_phone,
                  isallphone: 3
                })
              }
            })
          }

        }


        // if(res.result.stores.length >=2){

        //    res.result.stores.forEach(item => {
        //     that.setData({
        //       isjrdphone:true,
        //       iscrdphone:true,
        //    })
        //       if(item.store_type == 1){
        //          that.setData({
        //            crdphoneNum:item.store_phone,
        //         })
        //         }else{
        //           that.setData({
        //             jrdphoneNum:item.store_phone,

        //           })
        //         }
        //     })
        //   }else{
        //     res.result.stores.forEach(item => {
        //       if(item.store_type == 1){
        //          that.setData({
        //            crdphoneNum:item.store_phone,
        //            iscrdphone:true,
        //            isjrdphone:false
        //         })
        //         }else{
        //           that.setData({
        //             jrdphoneNum:item.store_phone,
        //             isjrdphone:true,
        //             iscrdphone:false,
        //           })

        //              }
        //     })
        //   }
        res.result.scheduled_time = app.moment(res.result.scheduled_time * 1000).format('YYYY-MM-DD HH:mm:ss');
        res.result.add_time = app.moment(res.result.add_time * 1000).format('YYYY-MM-DD HH:mm:ss');
        if (res.result.prom_type == '6') {
          if (res.result.teamFollow == '') {
            // 如果为空
            res.result.listId = res.result.teamFound.found_id
          } else {
            // 如果不为空
            res.result.listId = res.result.teamFollow.found_id
          }
        }

        that.setData({
          details: res.result
        })
      } else {
        throw res.msg
      }
    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
    })
  },

  doPay(e) { //立即支付
    const that = this;
    let submit = that.data.submit;
    if (submit == 1) {
      submit += 1;
      that.setData({
        submit: submit
      })
      setTimeout(() => {
        that.setData({
          submit: 1
        })
      }, 2000)
      let money = that.data.details.order_amount;
      let sn = that.data.details.master_order_sn;
      let json = {
        token: app.globalData.token,
        trade_type: "JSAPI",
        master_order_sn: sn,
        account: money
      }
      let jsonData = app.utils.getSignData(json);
      if (that.data.curindex == 1) {
        app.utils.post(app.api.reqUrls.carddoPay, jsonData).then(res => {
          if (res.status == 1) {
            wx.showToast({
              title: '支付成功',
              icon: "none"
            })
            app.getInfo(app.globalData.token)
            that.getDetails();
          } else if (res.status == -1001) {
            wx.showModal({
              title: '温馨提示',
              content: '您还没有可使用的会员卡，是否去绑卡？',
              confirmText: '去绑卡',
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: -1,
                    success() {
                      wx.navigateTo({
                        url: `/page/details/pages/cardHolder/cardHolder?where=1`,
                      })
                    }
                  })
                } else if (res.cancel) {

                }
              }
            })
          } else if (res.status == -1002) {
            wx.showModal({
              title: '温馨提示',
              content: '会员卡余额不足，是否去充值？',
              confirmText: '去充值',
              success: function (shres) {
                if (shres.confirm) {
                  wx.navigateBack({
                    delta: -1,
                    success() {
                      wx.navigateTo({
                        url: '/page/details/pages/cardRecharge/cardRecharge?factamount=' + res.result.factamount,
                      })
                    }
                  })
                } else if (shres.cancel) {

                }
              }
            })
          } else {
            throw res.msg
          }
        }).catch(err => {
          app.showInfo(err.toString())
        })
      } else {
        app.utils.post(app.api.reqUrls.doPay, jsonData).then(res => {
          if (res.status == 1) {
            console.log("支付信息：", res.result)
            wx.requestPayment({ // 调取支付
              timeStamp: res.result.timeStamp.toString(),
              nonceStr: res.result.nonceStr,
              package: res.result.package,
              signType: res.result.signType,
              paySign: res.result.sign,
              success(res) {
                if (res.errMsg == "requestPayment:ok") {
                  app.getInfo(app.globalData.token)
                  that.getDetails();
                } else {
                  throw res.errMsg;
                }
              },
              fail(res) {
                console.log(res)
              }
            })

          } else {
            throw res.msg
          }
        }).catch(err => {
          app.showInfo(err.toString())
        })
      }
    }
  },
  //联系客服
  servicePhone(e) {
    if (e.currentTarget.dataset.tel) {
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.tel //仅为示例，并非真实的电话号码
      })
    } else {
      wx.showToast({
        title: '当前店铺没有留下联系方式',
        icon: "none"
      })
    }

  },
  //联系客服
  popSelect: function (e) {

    wx.showActionSheet({
      itemList: e.currentTarget.dataset.tel,
      success: function (res) {
        console.log(res.tapIndex);
        var str = e.currentTarget.dataset.tel[res.tapIndex];
        var str_new = str.substring(6, str.length) //取电话字符
        console.log(str_new);
        wx.makePhoneCall({
          phoneNumber: str_new //仅为示例，并非真实的电话号码
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    console.log(options)
    that.setData({
      id: options.id,
      sn: options.sn,
      storeid: options.store_id,
    })
    //关闭系统分享
    wx.hideShareMenu();
  },

  onShow() {
    const that = this;
    that.getDetails();
  },
  //弹出弹框
  submitOrdershow() {
    const that = this;
    // this.setData({
    //   showModal: true
    // })
    let money = that.data.details.order_amount;
    let sn = that.data.details.master_order_sn;
    let json = {
      token: app.globalData.token,
      trade_type: "JSAPI",
      master_order_sn: sn,
      account: money
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.doPay, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        let preOrderId = res.result.pre_order
        let merchantId = res.result.ls_merchant_id
        let opAppId = res.result.open_appid
        wx.openEmbeddedMiniProgram({
          appId: opAppId, // 你要打开的小程序appid
          extraData: { //给B小程序传的参数
            autoPay: 1,
          },
          path: `pages/plugin/pay?preOrderId=${preOrderId}&merchantId=${merchantId}`, // 打开的页面路径，如果为空则打开首页
          envVersion: 'release', // 要打开的小程序版本 develop 开发版 trial 体验版 release 正式版
          success(resData) {
            console.log(resData, 11111)
            // 打开成功

            var listener = (props) => {
              console.log(props, 111)
              console.log(props.referrerInfo, 222)
              console.log(props.referrerInfo.extraData, 333)
              if (!props.referrerInfo.hasOwnProperty('extraData')) {
                console.log('错误')
                that.getDetails();
                console.log(1234)
                if (listener) {
                  console.log(4567)
                  wx.offAppShow(listener)
                }
              }
              if (props.referrerInfo.extraData.payStatus === '0') {
                console.log('支付失败')
                //支付失败
                //.....
                wx.showModal({
                  content: '付款失败',
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {
                    if (e.confirm) {
                      that.getDetails();
                    }
                  }
                })
              }
              if (props.referrerInfo.extraData.payStatus === '1') {
                console.log('支付成功')
                //支付成功
                //.....
                that.getDetails();
              }
              if (props.referrerInfo.extraData.payStatus === '3') {
                console.log('用户取消支付')
                //用户取消支付(订单状态流转为已关闭)
                //......
                that.getDetails();
              }
              console.log(123)
              if (listener) {
                console.log(456)
                wx.offAppShow(listener)
              }
            };
            wx.onAppShow(listener)
          },
          fail(e) {
            console.log(e, 999999)
            // 打开失败
          },
        })
      } else {
        wx.showModal({
          content: res.msg,
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {
            that.getDetails();
          }
        })
      }
    })
  },
  onHide() {
    const that = this;
    that.setData({
      hiddenLoading: true
    })
  },
  /**
   * 隐藏模态对话框
   */
  hideModal() {
    this.setData({
      showModal: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel() {
    this.hideModal();
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function () {
    this.hideModal();
    this.doPay();
  },

  choose(e) {
    var index = e.currentTarget.dataset.index
    var value = e.currentTarget.dataset.name
    console.log(value, index)
    this.setData({
      curindex: index
    })
  }
})